#include "../../Demo/Server.hpp"

uint64_t conn_id = 0;
std::unordered_map<int, PtrConnection> _conns;
EventLoop baseloop;
LoopThreadPool *loop_pool; 

void ConnectionDestory(const PtrConnection& conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("new connection : %p", conn.get());
}

void OnMessage(const PtrConnection& conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReadPostion());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
}

void NewConnection(int newfd)
{
    conn_id++;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, newfd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestory, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(5);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("main thread");
}

int main()
{
    loop_pool = new LoopThreadPool(&baseloop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&baseloop, 8080);
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();
    baseloop.Start();
    return 0;
}